<template>
  <div class="dashboard-container">
    <!-- 侧边栏 -->
    <aside class="sidebar">
      <div class="logo">
        <h2>管理后台</h2>
      </div>
      <nav class="nav-menu">
        <div class="menu-item" @click="navigateTo('/dashboard')">
          <i class="icon">📊</i>
          <span>仪表盘</span>
        </div>
        <div class="menu-item" @click="navigateTo('/dashboard')">
          <span>📊</span>
          <span>数据统计</span>
        </div>
        <div class="menu-item" @click="navigateTo('/user-audit')">
          <span>👥</span>
          <span>用户审核</span>
        </div>
        <div class="menu-item" @click="navigateTo('/user-management')">
          <span>👤</span>
          <span>用户管理</span>
        </div>
        <div class="menu-item" @click="navigateTo('/team-management')">
          <span>⚡</span>
          <span>队伍管理</span>
        </div>
        <div class="menu-item" @click="navigateTo('/homepage-editor')">
          <span>🏠</span>
          <span>主页编辑</span>
        </div>
        <div class="menu-item active" @click="navigateTo('/system-notifications')">
          <span>📢</span>
          <span>通知管理</span>
        </div>
        <div class="menu-item" @click="navigateTo('/news-management')">
          <span>📰</span>
          <span>新闻管理</span>
        </div>
        <div class="menu-item" @click="navigateTo('/event-management')">
          <span>🏆</span>
          <span>赛事管理</span>
        </div>
      </nav>
      <div class="user-info">
        <div class="user-avatar">👤</div>
        <div class="user-details">
          <div class="user-name">{{ adminName }}</div>
          <div class="user-role">账号</div>
        </div>
        <button class="logout-btn" @click="handleLogout">
          退出登录
        </button>
      </div>
    </aside>

    <!-- 主要内容区域 -->
    <main class="content">
      <div class="page-header">
        <h2>系统通知管理</h2>
        <div class="header-actions">
          <button class="create-btn" @click="goToPublish">发布通知</button>
        </div>
      </div>

      <!-- 筛选器 -->
      <div class="filter-section">
        <div class="filter-item">
          <label>状态筛选：</label>
          <select v-model="filterStatus" @change="handleFilterChange">
            <option value="">全部</option>
            <option value="1">已发布</option>
            <option value="0">草稿</option>
          </select>
          <div class="filter-item" >
          <button class="refresh-btn" @click="refreshNotifications">
            <i class="icon">🔄</i>
            刷新
          </button>
        </div>
        </div>
    
      </div>

      <!-- 通知列表 -->
      <div class="notifications-list">
        <div v-if="loading" class="loading">
          加载中...
        </div>
        
        <div v-else-if="notifications.length === 0" class="empty-state">
          <div class="empty-icon">📢</div>
          <p>暂无通知</p>
        </div>
        
        <div v-else class="notifications-cards">
          <div 
            v-for="notification in notifications" 
            :key="notification.id" 
            class="notification-card"
          >

            
            <!-- 通知主体内容 -->
            <div class="notification-main">
              <!-- 左侧通知信息 -->
              <div class="notification-info">
                <div class="notification-header">
                  <h3 class="notification-title">
                    {{ notification.title }}
                  </h3>
                  <div class="notification-meta">
                    <span class="publish-time">{{ formatDate(notification.publishTime) }}</span>
                    <span class="view-count">👁 {{ notification.viewCount }}</span>
                    <span class="status" :class="getStatusClass(notification.status)">
                      {{ getStatusText(notification.status) }}
                    </span>
                  </div>
                </div>

                <div class="notification-summary" v-if="notification.summary">
                  {{ notification.summary }}
                </div>
              </div>

              <!-- 右侧操作按钮 -->
              <div class="notification-actions">
                <button class="view-btn" @click="viewNotification(notification)">查看</button>
                <button class="edit-btn" @click="editNotification(notification)">编辑</button>
                <button class="delete-btn" @click="deleteNotification(notification)">删除</button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div class="pagination" v-if="totalPages > 1">
        <button 
          class="page-btn" 
          @click="changePage(currentPage - 1)"
          :disabled="currentPage === 1"
        >
          上一页
        </button>
        <span class="page-info">{{ currentPage }} / {{ totalPages }}</span>
        <button 
          class="page-btn" 
          @click="changePage(currentPage + 1)"
          :disabled="currentPage === totalPages"
        >
          下一页
        </button>
      </div>
    </main>

    <!-- 查看通知弹窗 -->
    <div v-if="showViewModal" class="modal-overlay" @click="closeViewModal">
      <div class="view-modal" @click.stop>
        <div class="modal-header">
          <h3>{{ viewingNotification?.title }}</h3>
          <button class="close-btn" @click="closeViewModal">×</button>
        </div>
        <div class="modal-content">
          <div v-if="viewingNotification?.loading" class="loading-state">
            <div class="loading-spinner">加载中...</div>
          </div>
          <div v-else>
            <div class="notification-meta">
              <span>发布时间：{{ formatDate(viewingNotification?.publishTime) }}</span>
              <span>浏览次数：{{ viewingNotification?.viewCount }}</span>
              <!-- <span v-if="viewingNotification?.publisherName">发布者：{{ viewingNotification.publisherName }}</span> -->
            </div>
            <div class="notification-content" v-html="viewingNotification?.content"></div>
          </div>
        </div>
      </div>
    </div>

    <!-- 删除确认弹窗 -->
    <div v-if="showDeleteModal" class="modal-overlay" @click="closeDeleteModal">
      <div class="delete-modal" @click.stop>
        <div class="modal-header">
          <h3>确认删除</h3>
          <button class="close-btn" @click="closeDeleteModal">×</button>
        </div>
        <div class="modal-content">
          <p>确定要删除通知"{{ deleteTarget?.title }}"吗？</p>
          <p class="warning-text">此操作不可恢复！</p>
          <div class="modal-actions">
            <button class="cancel-btn" @click="closeDeleteModal">取消</button>
            <button class="confirm-btn" @click="confirmDelete" :disabled="deleting">
              {{ deleting ? '删除中...' : '确认删除' }}
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 消息提示 -->
    <div v-if="showMessage" class="message-toast" :class="messageType">
      {{ messageText }}
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useTokenStore } from '@/stores/token.js'
import { useAdminStore } from '@/stores/admin.js'
import {
  getSystemNotificationsService,
  getSystemNotificationService,
  deleteSystemNotificationService
} from '@/api/admin.js'

const router = useRouter()
const tokenStore = useTokenStore()
const adminStore = useAdminStore()

// 管理员姓名
const adminName = computed(() => {
  return adminStore.getAdminName()
})

// 数据状态
const loading = ref(false)
const notifications = ref([])
const filterStatus = ref('')

// 分页配置
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0
})

// 状态常量
const NOTIFICATION_STATUS = {
  DRAFT: 0,
  PUBLISHED: 1,
  DELETED: -1
}

// 状态文本映射
const getStatusText = (status) => {
  switch(status) {
    case 0: return '草稿'
    case 1: return '已发布'
    case -1: return '已删除'
    default: return '未知'
  }
}

// 计算总页数
const totalPages = computed(() => {
  return Math.ceil(pagination.value.total / pagination.value.pageSize)
})

// 弹窗状态
const showViewModal = ref(false)
const showDeleteModal = ref(false)
const viewingNotification = ref(null)
const deleteTarget = ref(null)
const deleting = ref(false)

// 消息提示
const showMessage = ref(false)
const messageText = ref('')
const messageType = ref('success')

// 导航到指定路由
const navigateTo = (path) => {
  router.push(path)
}

// 退出登录
const handleLogout = () => {
  tokenStore.removeToken()
  adminStore.clearAdminInfo()
  router.push('/login')
}

// 显示消息
const showMessageToast = (text, type = 'success') => {
  messageText.value = text
  messageType.value = type
  showMessage.value = true
  setTimeout(() => {
    showMessage.value = false
  }, 3000)
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN')
}

// 获取状态样式类
const getStatusClass = (status) => {
  switch (status) {
    case 1: return 'published'
    case 0: return 'draft'
    case -1: return 'deleted'
    default: return ''
  }
}



// 加载通知列表
const loadNotifications = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.value.current,
      size: pagination.value.pageSize
    }

    // 添加状态筛选
    if (filterStatus.value !== '') {
      params.status = filterStatus.value
    }

    const result = await getSystemNotificationsService(params)
    if (result.code === 200) {
      notifications.value = result.data.list || []
      pagination.value.total = result.data.total || 0
    } else {
      showMessageToast(result.message || '加载失败', 'error')
    }
  } catch (error) {
    console.error('加载通知列表失败:', error)
    showMessageToast('加载失败，请稍后重试', 'error')
  } finally {
    loading.value = false
  }
}

// 分页切换
const changePage = (page) => {
  if (page >= 1 && page <= totalPages.value) {
    pagination.value.current = page
    loadNotifications()
  }
}

// 筛选变化处理
const handleFilterChange = () => {
  pagination.value.current = 1 // 重置到第一页
  loadNotifications()
}

// 页面大小变化处理
const handlePageSizeChange = () => {
  pagination.value.current = 1 // 重置到第一页
  loadNotifications()
}

// 刷新通知列表
const refreshNotifications = () => {
  loadNotifications()
}

// 获取页码数组（用于分页显示）
const getPageNumbers = () => {
  const total = totalPages.value
  const current = pagination.value.current
  const pages = []

  if (total <= 7) {
    // 总页数小于等于7，显示所有页码
    for (let i = 1; i <= total; i++) {
      pages.push(i)
    }
  } else {
    // 总页数大于7，显示省略号
    if (current <= 4) {
      // 当前页在前面
      for (let i = 1; i <= 5; i++) {
        pages.push(i)
      }
      pages.push('...')
      pages.push(total)
    } else if (current >= total - 3) {
      // 当前页在后面
      pages.push(1)
      pages.push('...')
      for (let i = total - 4; i <= total; i++) {
        pages.push(i)
      }
    } else {
      // 当前页在中间
      pages.push(1)
      pages.push('...')
      for (let i = current - 1; i <= current + 1; i++) {
        pages.push(i)
      }
      pages.push('...')
      pages.push(total)
    }
  }

  return pages
}

// 跳转到发布页面
const goToPublish = () => {
  router.push('/publish-notification')
}

// 查看通知
const viewNotification = async (notification) => {
  try {
    // 显示加载状态
    viewingNotification.value = { ...notification, loading: true }
    showViewModal.value = true

    // 调用API获取完整的通知详情
    const result = await getSystemNotificationService(notification.id)
    if (result.code === 200) {
      viewingNotification.value = result.data
    } else {
      showMessageToast(result.message || '获取通知详情失败', 'error')
      closeViewModal()
    }
  } catch (error) {
    console.error('获取通知详情失败:', error)
    showMessageToast('获取通知详情失败，请稍后重试', 'error')
    closeViewModal()
  }
}

// 编辑通知
const editNotification = (notification) => {
  router.push(`/edit-notification/${notification.id}`)
}



// 删除通知
const deleteNotification = (notification) => {
  deleteTarget.value = notification
  showDeleteModal.value = true
}

// 确认删除
const confirmDelete = async () => {
  if (!deleteTarget.value) return
  
  deleting.value = true
  try {
    const result = await deleteSystemNotificationService(deleteTarget.value.id)
    if (result.code === 200) {
      showMessageToast('删除成功')
      closeDeleteModal()
      await loadNotifications()
    } else {
      showMessageToast(result.message || '删除失败', 'error')
    }
  } catch (error) {
    console.error('删除通知失败:', error)
    showMessageToast('删除失败，请稍后重试', 'error')
  } finally {
    deleting.value = false
  }
}

// 关闭查看弹窗
const closeViewModal = () => {
  showViewModal.value = false
  viewingNotification.value = null
}

// 关闭删除弹窗
const closeDeleteModal = () => {
  showDeleteModal.value = false
  deleteTarget.value = null
}

// 页面初始化
onMounted(() => {
  if (!tokenStore.token) {
    router.push('/login')
    return
  }
  loadNotifications()
})
</script>

<style scoped>
@import '@/assets/css/Management.css';
</style>